package com.example.fragmenttest.Fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.fragmenttest.Bean.User;
import com.example.fragmenttest.LoginActivity;
import com.example.fragmenttest.R;

import org.litepal.LitePal;
public class ThirdFragment extends Fragment {
    private EditText oldpsdedit ,newpsdedit ;
    private Button changepsdbtn ;
    public ThirdFragment() {
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        View view=inflater.inflate(R.layout.fragment_third, container, false);
        initView(view);
        setListener();
        return  view ;
    }

    private void setListener() {
        changepsdbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String psd_old =oldpsdedit.getText().toString();
                String psd_new =newpsdedit.getText().toString() ;
                SharedPreferences sp=getActivity().getSharedPreferences("userinfo",Context.MODE_PRIVATE);
                int uid=sp.getInt("userid",-1);
                String password =sp.getString("password","");
                if (psd_old.equals(password)){
                    //数据库的更新
                    User user =LitePal.find(User.class,uid) ;//根据id取出用户
                    user.setPassword(psd_new);//更改密码
                    user.save() ;
                    showToast("修改密码成功");
                    Intent intent =new Intent(getContext(), LoginActivity.class);
                    startActivity(intent);
                    getActivity().finish();//碎片不可以直接结束，所以利用
                }else {
                    showToast("原密码输入错误");

                }
            }
        });

    }

    private void showToast(String str ){

        Toast.makeText(getContext(),str, Toast.LENGTH_SHORT).show();


    }


    private void initView(View view) {
        //碎片找不到，必须传参 View view
        oldpsdedit= view.findViewById(R.id.oldpsdedit);
        newpsdedit=view.findViewById(R.id.newpsdedit);
        changepsdbtn=view.findViewById(R.id.changepsdbtn);



    }
}
